package com.ruibang.glass.equipment.controller;

import cn.hutool.core.date.DateUtil;
import com.ruibang.glass.common.constants.CommonErrorCode;
import com.ruibang.glass.equipment.constant.Constants;
import com.ruibang.glass.equipment.domain.req.device.DeviceAllPageReq;
import com.ruibang.glass.equipment.entity.device.InventoryManagement;
import com.ruibang.glass.equipment.entity.device.ScrapReport;
import com.ruibang.glass.equipment.service.InventoryManagementService;
import com.ruibang.glass.equipment.service.ValiDateService;
import com.teaming.cloud.framework2.common.model.ResultBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 测量体系/仪表台账
 * </p>
 *
 * @author mameng
 * @since 2024-03-20
 */
@RestController
@RequestMapping("/api/equipment/inventory/management")
@Api(value = "入库管理")
public class InventoryManagementController {
    @Autowired
    private InventoryManagementService inventoryManagementService;

    @PostMapping("list")
    @ApiOperation(value = "检修工作单列表", response = ResultBody.class)
    public ResultBody getBoilerList(@RequestBody DeviceAllPageReq deviceAllPageReq) {
        return ResultBody.success(inventoryManagementService.getPointRecordList(deviceAllPageReq));
    }

    @PostMapping("addOrUpdateCheck")
    @ApiOperation(value = "修改添加", response = ResultBody.class)
    public ResultBody addChild(@RequestBody InventoryManagement repairWorkOrder) {
        return ResultBody.success(inventoryManagementService.addOrUpdateCheck(repairWorkOrder));
    }


    //
    @PostMapping("deleteAll")
    @ApiOperation(value = "删除", response = ResultBody.class)
    public ResultBody deleteAll(@RequestBody InventoryManagement repairWorkOrder) {
        inventoryManagementService.lambdaUpdate().set(InventoryManagement::getIsDelete, Constants.ONE_STR).eq(InventoryManagement::getId, repairWorkOrder.getId()).update();
        return ResultBody.success();
    }


    @PostMapping("getOne")
    @ApiOperation(value = "查看详情", response = ResultBody.class)
    public ResultBody getOne(@RequestBody InventoryManagement repairWorkOrder) {
        return ResultBody.success(inventoryManagementService.getById(repairWorkOrder.getId()));
    }


    @GetMapping("getNameAndId")
    @ApiOperation(value = "获取入库名称和Id", response = ResultBody.class)
    public ResultBody getNameAndId() {
        return inventoryManagementService.getNumberAndName();
    }


    @GetMapping("getNumberAndId")
    @ApiOperation(value = "获取入库数量和Id", response = ResultBody.class)
    public ResultBody getNumberAndId() {
        return inventoryManagementService.getNumberAndId();
    }

    @GetMapping("getNumberAndName")
    @ApiOperation(value = "获取入库数量和Id", response = ResultBody.class)
    public ResultBody getNumberAndName() {
        return inventoryManagementService.getNumberAndName();
    }


    // 导入
    @PostMapping("importExcel")
    @ApiOperation(value = "导入", response = ResultBody.class)
    public ResultBody importExcel(@RequestPart("files") MultipartFile file, HttpServletRequest request) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String contentType = file.getContentType();
        System.out.println("文件类型是===========" + contentType);
        String fileName = file.getOriginalFilename();
        System.out.println("文件名字是===========" + fileName);
        try {
//            if (!fileName.endsWith(".xlsx")) {
//                return ResultBody.fail(300, "文件格式不正确！请使用.Xlsx格式");
//            }
            if (file.isEmpty()) {
                return ResultBody.fail(310, "文件为空！");
            }
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);
            //根据页面index 获取sheet页
            Sheet sheet = wb.getSheetAt(0);
            //获取sheet页共有多少行
            int totalRos = sheet.getPhysicalNumberOfRows();
            System.out.println("=========总行数为：" + totalRos);
            if (totalRos < 2) {
                return ResultBody.fail(300, "文件禁止为只有表头！");
            }
            List<InventoryManagement> list = new ArrayList<>();
            for (int i = 1; i < totalRos; i++) {
                int lastCellNum = sheet.getRow(i).getLastCellNum();
                if (lastCellNum < 7) {
                    return ResultBody.fail(CommonErrorCode.MONITOR_DATA_EXPORT_IN_FAIL.getCode(), CommonErrorCode.MONITOR_DATA_EXPORT_IN_FAIL.message);
                }
                //sheet.getRow(i).getCell(j).toString()
                System.out.println("=========第" + i + "行的数据如下：=========");
                InventoryManagement instrumentRegister = new InventoryManagement();
                instrumentRegister.setSparePartsName(sheet.getRow(i).getCell(0).toString());
                instrumentRegister.setModel(sheet.getRow(i).getCell(1).toString());
                instrumentRegister.setUnit(sheet.getRow(i).getCell(2).toString());
                instrumentRegister.setInboundQuantity((int) sheet.getRow(i).getCell(3).getNumericCellValue());
                if (ValiDateService.isTimeFormat(sheet.getRow(i).getCell(4).toString()) || ValiDateService.isValidDate(sheet.getRow(i).getCell(4).toString())) {
                    instrumentRegister.setInboundTime(DateUtil.parse(sheet.getRow(i).getCell(4).toString()).toLocalDateTime());
                } else {
                    return ResultBody.fail(300, "入库时间 格式有误！");
                }
                instrumentRegister.setWarehouseName(sheet.getRow(i).getCell(5).toString());
                instrumentRegister.setShelfNumber(sheet.getRow(i).getCell(6).toString());
                if (sheet.getRow(i).getCell(7) != null) {
                    instrumentRegister.setIssueNumber(sheet.getRow(i).getCell(7).toString());
                }
                list.add(instrumentRegister);
            }
            inventoryManagementService.saveBatch(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultBody.success("成功");
    }


}
